package com.bianpai.rollback;

import com.bianpai.core.Flow;
import com.bianpai.core.FlowContext;
import com.bianpai.core.Node;
import com.bianpai.core.NodeResult;
import com.bianpai.log.FlowLogger;

import java.util.ArrayList;
import java.util.List;

/**
 * 默认回滚策略，按照节点执行的相反顺序进行回滚
 */
public class DefaultRollbackStrategy implements RollbackStrategy {
    
    @Override
    public void rollback(Flow flow, FlowContext context, FlowLogger logger) {
        logger.logRollbackStart(flow, context);
        
        // 获取已执行成功的节点
        List<Node> nodesToRollback = new ArrayList<>();
        for (Node node : flow.getNodes()) {
            NodeResult result = context.getNodeResult(node.getId());
            if (result != null && result.isSuccess() && node.isRollbackable()) {
                nodesToRollback.add(node);
            }
        }
        
        // 按照相反的顺序回滚
        for (int i = nodesToRollback.size() - 1; i >= 0; i--) {
            Node node = nodesToRollback.get(i);
            logger.logNodeRollbackStart(node, context);
            
            try {
                boolean rollbackSuccess = node.rollback(context);
                logger.logNodeRollbackComplete(node, context, rollbackSuccess);
            } catch (Exception e) {
                logger.logNodeRollbackError(node, context, e);
            }
        }
        
        logger.logRollbackComplete(flow, context);
    }
}